<template>
  <div class="person-info-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本资料" name="first">
        <div class="basicMaterial">
          <!-- 头像 -->
          <div class="avatar-box">
            <el-upload
              action="http://192.168.1.125:8080/home/home/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imgSrc" :src="imgSrc" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <!-- 其他数据 -->
          <common-form
            :form="formData"
            :formTemplate="formTemplate"
          ></common-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="密码管理" name="second">
        <el-form
          ref="form"
          label-position="left"
          :model="passwords"
          label-width="120px"
          status-icon
          :rules="rules"
        >
          <el-form-item label="旧密码">
            <el-input show-password v-model="passwords.oldPassword"></el-input>
          </el-form-item>
          <el-form-item label="新密码">
            <el-input show-password v-model="passwords.newPassword1"></el-input>
          </el-form-item>
          <el-form-item label="再次输入新密码">
            <el-input show-password v-model="passwords.newPassword2"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="密保管理" name="third">
        <!-- 密保管理的地方 -->
        <el-form :model="security" label-width="80px">
          <!-- 选择一个密保问题 -->
          <el-form-item label="密保问题">
            <el-select
              v-model="security.question"
              placeholder="选择一个密保问题"
            >
              <el-option
                v-for="item in questions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 输入密保答案 -->
          <el-form-item label="密保答案">
            <el-input
              v-model="security.answer"
              placeholder="输入答案"
            ></el-input
          ></el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="用户画像" name="fourth">用户画像</el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import CommonForm from "./CommonForm.vue";
import { uploadImage } from "@/mixin";
import {
  createInput,
  createSelect,
  createDatePicker,
} from "@/utils/FormCreator";
import ManOrWoman from "@/utils/ManOrWoman";
import {
  alterPersonInfo,
  alterPasswordByOldPwd,
  setSecretQuestion,
} from "@/services/user";
import { Message } from "element-ui";
import commonID from "@/utils/commonID";
import PubSub from "pubsub-js";
const studentFormTemplate = [
  {
    type: "input",
    label: "账号",
    key: "student_id",
    disabled: true,
  },
  {
    type: "input",
    label: "用户名",
    key: "username",
  },
  {
    type: "select",
    label: "性别",
    key: "gender",
    opts: [
      {
        label: "男",
        value: "男",
      },
      {
        label: "女",
        value: "女",
      },
    ],
  },
];
const teacherFormTemplate = [
  createInput("账号", "teacher_id", true),
  createInput("用户名", "username"),
  createSelect("性别", "gender", ManOrWoman),
  createDatePicker("入职时间", "appoint_start_date"),
];

function handlePromiseResult(promise, successMessage) {
  promise.then((res) => {
    if (res.data.code == 200) {
      Message.success(successMessage);
    }
  });
}

export default {
  components: { CommonForm },
  name: "PersonalInformation",
  mixins: [uploadImage],
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwords.newPassword1) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      passwordManageFormTemplate: [
        createInput("旧密码", "oldPassword"),
        createInput("新密码", "newPassword1"),
        createInput("确认新密码", "newPassword2"),
      ],
      passwords: {},
      activeName: "first",
      isChange: true,
      // imageUrl: "",
      security: {},
      questions: [
        "您父亲的姓名",
        "您母亲的姓名",
        "您初中毕业的学校名",
        "您高中毕业的学校名",
        "您大学毕业的学校名",
        "您朋友的名字",
      ],
      formData: null,
      formTemplate: null,
      rules: {
        oldPassword: [{ required: true, trigger: "blur" }],
        newPassword1: [{ required: true, trigger: "blur" }],
        newPassword2: [
          { required: true, trigger: "blur", validator: validatePass2 },
        ],
      },
    };
  },
  created() {
    this.user = JSON.parse(localStorage.getItem("userInfo"));
    const { role } = this.user;
    this.uid = this.user[`${role}_id`];

    if (role == "student") {
      this.formTemplate = studentFormTemplate;
    } else if (role == "teacher") {
      this.formTemplate = teacherFormTemplate;
    } else {
      console.log("暂不支持教员个人信息查看");
    }

    this.axios
      .get(`${this.$reqPrefix}/getPersonInfo`, {
        params: {
          role,
          [`${role}_id`]: this.uid,
        },
      })
      .then((res) => {
        console.log("res: ", res);
        this.formData = res.data.data;
      });

    // 订阅一个dosomething的消息
  },
  methods: {
    submitChange() {
      // 1. 根据当前的标签页，获取不同的数据进入不同的确定流程
      // 1.3 如果是密保管理，就去调用修改密保问题和密保答案的逻辑
      // 1.4 用户画像不可以被确定
      const { role } = this.user;
      switch (this.activeName) {
        case "first": {
          // 1.1 如果是基本信息，那么就调用修改基本信息的接口
          // handlePromiseResult(alterPersonInfo(this.formateData));
          const { role } = JSON.parse(localStorage.getItem("userInfo"));
          console.log(this.formData);
          alterPersonInfo({ ...this.formData, avatar: this.imgSrc, role });
          break;
        }
        case "second": {
          // 1.2 如果是密码管理，就做校验然后提交修改密码的逻辑

          const { oldPassword, newPassword1: newPassword } = this.passwords;

          alterPasswordByOldPwd(
            role,
            this.user[commonID(role)],
            oldPassword,
            newPassword
          ).then((res) => {
            if (res.data.code == 200) {
              Message.success("修改成功，请重新登录");
              localStorage.removeItem("userInfo");
              this.$router.replace("/login");
            }
          });
        }
        case "third": {
          const { question, answer } = this.security;
          handlePromiseResult(
            setSecretQuestion(role, this.user[commonID(role)], question, answer)
          );
          break;
        }
        default:
          return;
      }
    },
    formateData() {
      // 对数据进行格式化
      if (this.activeName == "passwordManage") {
        // 如果是修改密码
        const oldPass = this.form[0].value;
        const newPass1 = this.form[1].value;
        const newPass2 = this.form[2].value;
        if (newPass1 !== newPass2) {
          alert("两次密码不一致");
          throw new Error("不一致的密码");
        }
        return {
          oldPass,
          newPass: newPass1,
        };
      } else {
        const res = {};
        this.form.forEach((e) => {
          const key = e.key;
          const value = e.value;
          res[key] = value;
        });
        res["avatar"] = this.imgSrc;
        return res;
      }
    },
    handleAvatarSuccess(res) {
      // this.imgSrc = res.data[0].url;
      // console.log(res);
      this.onUploaded(res.data[0].url);
    },
    beforeAvatarUpload(file) {
      this.beforeUpload(file);
    },
  },
  mounted() {
    this.pubId = PubSub.subscribe("submitUserInfoChange", (_, data) => {
      // a是消息名，b是真正的参数
      // console.log(this); // 当前的组件实例对象vc
      // console.log("有人发布了消息");
      this.submitChange();
    });
  },
  // 被销毁前取消订阅消息
  beforeDestroy() {
    PubSub.unsubscribe(this.pubId);
  },
};
</script>

<style lang='less' scoped>
.person-info-container {
  width: 90%;
}
.el-form-item {
  margin-bottom: 5px;
  .el-select {
    width: 100%;
  }
}
.avatar-box {
  width: 100px;
  height: 100px;
  background-color: #fefefe;
  margin-bottom: 10px;
  // background-repeat: 6px;
  border: 1px dashed #d9d9d9;

  border-radius: 6px;
  &:hover {
    border-color: #409eff;
  }
  &:deep(.el-upload) {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #fefefe;
    img {
      width: 100%;
      object-fit: cover;
    }

    .avatar-uploader-icon {
      width: 100%;
      font-size: 28px;
      color: #8c939d;
      line-height: 100px;
      text-align: center;
    }
  }
}
</style>